﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ShutDownX
{
    partial class ShutDownX : ServiceBase
    {
        DateTime myTime;
        List<string> myProcess = null;
        string LogPath = "";
        protected System.Timers.Timer myTimer = new System.Timers.Timer();

        public ShutDownX()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            try
            {
                myTime = DateTime.Parse(ConfigurationManager.AppSettings["Time"]);
                myProcess = new List<string>(ConfigurationManager.AppSettings["Processes"].ToString().ToLower().Split('|'));
                LogPath = ConfigurationManager.AppSettings["LogPath"];

                myTimer.Interval = 1000;
                myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
                myTimer.Start();
            }
            catch (Exception ex)
            {
                OutLog(ex.Message);
            }
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }

        private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            TimeSpan diffTime = myTime.Subtract(DateTime.Now);
            if (diffTime.TotalMilliseconds < 1)
            {
                ShutDown();
                myTimer.Stop();
            }
        }

        private void ShutDown()
        {
            Process[] processes = Process.GetProcesses();

            foreach (Process p in processes)
            {
                try
                {
                    if (myProcess.Contains(p.MainModule.ModuleName.ToLower()))
                    {
                        if (!p.CloseMainWindow()) OutLog("进程关闭失败：" + p.MainModule.ModuleName);
                    }
                }
                catch
                {
                    continue;
                }
            }
            //Process.Start("shutdown.exe", "-f -s -t 120");
            OutLog("120秒后系统关机");
        }

        public void OutLog(string txt)
        {
            FileStream fs = null;
            StreamWriter text = null;
            string LogFile = LogPath + @"\ShutDownX.log";

            try
            {
                fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
                text = new StreamWriter(fs);
                text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + txt);
                text.Flush();
            }
            catch
            {
            }
            finally
            {
                if (fs != null) fs.Dispose();
            }
        }
    }
}
